package com.velvetantler.weather.adapter

import android.util.SparseArray
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.velvetantler.weather.view.home.HomeFragment
import com.velvetantler.weather.view.mine.MeFragment
import com.velvetantler.weather.view.star.StarFragment

class ViewPagerAdapter(fragmentActivity: FragmentActivity) :
    FragmentStateAdapter(fragmentActivity) {

    private val fragmentCacheList = SparseArray<Fragment>()
    override fun createFragment(position: Int): Fragment {
        val fragment = fragmentCacheList[position]
        return if (fragment == null) {
            val newFragment = when (position) {
                0 -> HomeFragment()
                1 -> StarFragment()
                2 -> MeFragment()
                else -> throw IllegalArgumentException("Invalid position: $position")
            }
            fragmentCacheList.set(position, newFragment)
            newFragment
        } else {
            fragment
        }
    }

    override fun getItemCount(): Int = 3

}